package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 设备Service业务层处理
 *
 * @author alexis
 * @date 2025-11-09
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param deviceDto 设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto) {
        //修改iot平台数据
        UpdateDeviceRequest request =new UpdateDeviceRequest();
    request.withDeviceId(deviceDto.getIotId());
        UpdateDevice updatedevice =new UpdateDevice();
        updatedevice.setDeviceName(deviceDto.getDeviceName());
        request.withBody(updatedevice);
        client.updateDevice(request);
// 修改 mysql数据
        Device device =new Device();
        BeanUtils.copyProperties(deviceDto,device);
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param iotId 设备主键
     * @return 结果
     */
    @Override
    public void deleteDeviceById(String iotId) {
        // 删除IOT平台
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        client.deleteDevice(request);
//删除mysql
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        remove(wrapper);


    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest request = new ListProductsRequest();
        //设置条数
        request.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //缓存数据
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String result = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT);
        if (StringUtils.isEmpty(result)) {
            return new ArrayList<ProductVo>();
        }
        List<ProductVo> list = JSONUtil.toList(result, ProductVo.class);
        return list;
    }

    /**
     * 设备注册
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称或者设备标识码是否重复
        LambdaQueryWrapper<Device> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Device::getDeviceName, deviceDto.getDeviceName())
                .or().eq(Device::getNodeId, deviceDto.getNodeId());
        long count = count(wrapper1);
        if (count > 0) {
            throw new BaseException("设备名称或者设备标识码重复");
        }

        //2.判断同一位置是否绑定了相同的产品
        LambdaQueryWrapper<Device> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType());
        count = count(wrapper2);
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //3.注册设备到华为IoT平台
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();

        addDevice.withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(new AuthInfo().withSecret(secret));

        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 设备注册失败");
        }

        //4.保存设备信息到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);
    }

    /**
     * 获取设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.查询数据库
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = getOne(wrapper);
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //2.调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = new ShowDeviceResponse();
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }

        //属性拷贝
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String, Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);
    }

    /**
     * 查询产品信息
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)){
            throw new BaseException("产品标识码不能为空");
        }
        //调用华为云物联网接口
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = null;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品信息失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            throw new BaseException("物联网接口 - 获取产品服务列表为空");
        }
        return AjaxResult.success(serviceCapabilities);
    }


}
